package dycloud.mabaoguo.User.controller;

import dycloud.mabaoguo.User.model.worldRank.History_WorldRank;
import dycloud.mabaoguo.User.model.Json_UserDataInfo;
import dycloud.mabaoguo.User.service.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.bson.Document;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WorldRankService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserInfoService userInfoService;

   // @Scheduled(cron = "0 0/10 * * * ?")  // 每10分钟执行一次
   @Scheduled(cron = "0 0 0 1 2,5,8,11 ?")  // 每三个月的第一天 00:00 执行
    public void handleWorldRankingReset() {
        try {
            // 获取当前世界排名数据
            List<Json_UserDataInfo> allUsers = userInfoService.getCurrentWorldRank();


            // 如果 allUsers 为 null 或 空，则跳过后续插入操作
            if (allUsers == null || allUsers.isEmpty()) {
                log.warn("No data found for world rank, skipping insertion.");
                return; // 跳过处理
            }

            String newTableName = "WorldRank_" + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));

            // 创建新表并插入数据
            // 1. 获取所有玩家数据
            List<Document> documents = allUsers.stream()
                    .map(this::convertToDocument)  // 将每个 Json_UserDataInfo 转换为 Document
                    .collect(Collectors.toList());

            // 2. 插入数据到新表
            mongoTemplate.getCollection(newTableName).insertMany(documents);
            log.info("48：Creat old WorldRank Success：{}", newTableName);

            // 获取 History_WorldRank 数据
            History_WorldRank historyWorldRank = mongoTemplate.findOne(new Query(), History_WorldRank.class);

            if (historyWorldRank == null) {
                // 如果 History_WorldRank 表中没有记录，创建新的记录
                historyWorldRank = new History_WorldRank();
                historyWorldRank.setTableNames(new ArrayList<>());
            }

            // 获取现有的 tableNames 列表
            List<String> tableNames = historyWorldRank.getTableNames();

            // 如果新表名已存在，替换为最新的表名，否则添加新表名
            if (tableNames.contains(newTableName)) {
                // 如果存在，替换为最新的
                tableNames.remove(newTableName);
            }
            // 始终将最新的表名放到列表的最后
            tableNames.add(newTableName);

            // 更新 History_WorldRank 表
            mongoTemplate.save(historyWorldRank);
            log.info("add new  table name  into   History_WorldRank");

            // 清空当前世界排名表
            mongoTemplate.dropCollection(Json_UserDataInfo.class);
            log.info("clear  userdata");

        } catch (Exception e) {
            log.error("79:error  {}", e.getMessage(), e);
        }
    }


    // 将 Json_UserDataInfo 转换为 Document
    private Document convertToDocument(Json_UserDataInfo userDataInfo) {
        Document document = new Document();
        document.put("playid", userDataInfo.getPlayid());
        document.put("winCount", userDataInfo.getWinCount());
        document.put("worldRank", userDataInfo.getWorldRank());
        return document;
    }
}
